package medium;

import java.util.*;

/**
 * @author liujianxin
 * @date 2019-08-03 22:24
 */
public class LengthOfLongestSubstring {

    public static void main(String[] args) {

        String s = "bpfbhmipx";

        Map<Character, Integer> table = new HashMap<>(s.length());
        int max = 0;
        for (int i = 0; i < s.length(); i++) {
            Character ch = s.charAt(i);
            Integer index;
            if ((index = table.get(ch)) != null) {
                max = table.size() > max ? table.size() : max;
                for (int j = index; j >= 0; j--) {
                    Character re = s.charAt(j);
                    Integer inr = table.get(re);
                    if (inr == null || inr > index || table.remove(re) == null) {
                        break;
                    }
                }
            }
            table.put(ch, i);
        }
        max = table.size() > max ? table.size() : max;
        System.out.println(max);


    }


    public int lengthOfLongestSubstring(String s) {
        s = s.replaceAll(" ", "");
        int[] table = new int[]{-1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1};
        int max = 0;
        int from = 0;
        int to = 0;
        int currMax = 0;
        for (int i = 0; i < s.length(); i++) {
            int c = s.charAt(i) - 'a';
            int index;
            if ((index = table[c]) == -1) {
                table[c] = i;
                currMax++;
                to = i;
            } else {
                for (; from <= to; from++) {
                    table[s.charAt(from) - 'a'] = -1;
                }
                table[index] = i;
                max = currMax > max ? currMax : max;
                currMax = 0;
                from = index;
            }

        }
        return currMax > max ? currMax : max;
    }
}
